package com.example.microinvestuser.service.user.impl;
import com.example.microinvestcommon.entity.Users;
import com.example.microinvestcommon.pojo.Result;
import com.example.microinvestcommon.service.RedisService;
import com.example.microinvestcommon.util.*;
import com.example.microinvestuser.dao.UserMapper;
import com.example.microinvestuser.service.user.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class AuthServiceImpl implements AuthService {
    private final UserMapper userMapper;

    private final RedisService redisService;

    private final SendMailUtil sendMailUtil;

    @Autowired
    public AuthServiceImpl(UserMapper userMapper, RedisService redisService, SendMailUtil sendMailUtil){
        this.userMapper=userMapper;
        this.redisService=redisService;
        this.sendMailUtil=sendMailUtil;
    }
    //登录服务1；
    @Override
    public Result<String> loginWithUsernamePasswordService(String userName, String password){
        // 检查用户是否存在
        boolean userExists = userMapper.existsByUsernameOrEmail(userName, null);
        if (!userExists) {
            return Result.error("用户不存在");
        }
        // 比对加密后的密码的哈希值
        String encryptedPassword = SHA256Util.getSHA256String(password);
        boolean passwordCorrect = userMapper.comparePassword(userName, encryptedPassword);
        if (!passwordCorrect) {
            return Result.error("用户名或密码错误");
        }
        // 生成 Token
        Map<String, Object> claims = new HashMap<>();
        Users user=userMapper.usersInfo(userName,null);
        claims.put("userId",user.getUserId());
        claims.put("userName", userName);
        claims.put("email",user.getEmail());
        String token;
        try {
            token = JwtUtil.genToken(claims);
        } catch (Exception e) {
            return Result.error("Token 生成失败，请稍后重试");
        }
        return Result.success(token);
    }

    //登录服务2:发送验证码；
    @Override
    public  Result<String> sendEmailService(String email){
        //检查邮箱格式是否正确
        Boolean emailFeasible= ValidatorUtil.isValidEmail(email);
        if(!emailFeasible){
            return Result.error("请输入正确的邮箱格式");
        }
        //检查邮箱是否存在
        boolean Emailexists=userMapper.existsByUsernameOrEmail(null,email);
        if(! Emailexists){
            return Result.error("未找到此邮箱，请检查是否输入正确");
        }
        //生成邮箱验证码
        String code= NumericCaptchaGeneratorUtil.generateNumericCaptcha();
        //发送验证码
        boolean right=sendMailUtil.sendEmail(email,code);
        if(!right){
            return Result.error("验证码发送错误");
        }
        //将code存入redis，时效五分钟
        redisService.storeVerificationCode(email, code);
        return Result.success("验证码已发送");
    }

    //登录服务2:验证验证码后进行登录操作；
    @Override
    public Result<String> verificationLoginCodeService(String email, String code) {
        boolean login=redisService.validateVerificationCode(email,code);
        if(login){
            // 生成 Token
            Map<String, Object> claims = new HashMap<>();
            Users user=userMapper.usersInfo(null,email);
            claims.put("userId",user.getUserId());
            claims.put("userName",user.getUserName());
            claims.put("email",email);
            String token;
            try {
                token = JwtUtil.genToken(claims);
            } catch (Exception e) {
                return Result.error("Token 生成失败，请稍后重试");
            }
            return Result.success(token);
        }
        else return Result.error("验证码错误或时效已过，请重试");
    }
}
